/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  TouchableHighlight,
  ToolbarAndroid,
  Dimensions,
  ListView,
  DeviceEventEmitter,
  Platform,
  NativeModules,
} from 'react-native';

import Common from '../../../component/common';
import ScreenUtils from '../../../component/ScreenUtils';
import Toast from 'react-native-root-toast';



const wechat=require('../../../images/wechat.png');
const weibo=require('../../../images/weibo.png');
const web=require('../../../images/newspaper.png');

import Article from '../../home/article';
import InfoSearch from '../../search/infoSearch';

export default class infoItem extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
  		dataSource: new ListView.DataSource({
          	rowHasChanged: (row1, row2) => row1 !== row2,
        	}),
  		showDeleteButton: this.props.showDeleteButton,
  		sectionTitle: this.props.sectionTitle,
  		rows :this.props.data,
  		classType:this.props.classType,
  		showTitle:this.props.showTitle,
      deleteArr:[],
      dataLength:this.props.data.length,
   };
   this.showTitle=this.state.showTitle;
   this.selectArr=[];
   this.openScroll=[]
  }
  
  componentWillUnmount() {
  	this.noDataEvent.remove();
  }
  componentWillReceiveProps(nextProps){
    
    if(parseInt(nextProps.classType) == 5 && nextProps.data != this.props.data) {
      this.setState({
        rows:nextProps.data,
        dataSource: this.state.dataSource.cloneWithRows(nextProps.data),
        dataLength:nextProps.data.length,
        showTitle:nextProps.showTitle,
        deleteArr:[]
      })
      this.selectArr=[];
      this.showTitle=this.state.showTitle;
    } 
    
  	if(this.openScroll.length>0){
      this.openScroll.map((item,key)=>{
          item.scrollTo({ x: 0, y: 0, animated: false });
          this.openScroll=[]
      })
    }
  }
  componentDidMount(){
  	this.setState({
  		dataSource: this.state.dataSource.cloneWithRows(this.state.rows),
  	})
  	this.noDataEvent = DeviceEventEmitter.addListener('noData',(data)=>{
      if(this.state.dataLength>0){
          this.setState({
           showTitle:true,
           noData:true,
          })
      }
      
  	});
  }
 handleDelete(rowIndex,entityId,target){
  	let formData = new FormData();
	formData.append("entityId",entityId);
	formData.append("userToken",this.props.userToken);
	Common.fetchData("POST", "/userCenter/collect/delete", formData, (responseData) => {
    let isShowTitle=this.state.dataLength;
    this.showTitle = isShowTitle==1 ? false : this.state.showTitle;
    this.selectArr.push(entityId);
    
      this.setState({
        deleteArr:this.selectArr,
        dataLength:isShowTitle-1,
        showTitle:this.showTitle
      });
    
    
    target.scrollTo({x: 0, y: 0, animated: false});
		// let arr= JSON.parse(JSON.stringify(this.state.rows));
		// arr.splice(rowIndex,1);
   
    // if(this.state.dataLength===0 ){
    //   DeviceEventEmitter.emit("dealCollection",this.state.classType);
    // }
		// if(this.state.dataLength>0 && this.state.dataLength-1 != rowIndex){
		// 	target.scrollTo({x: 0, y: 0, animated: false});
		// }
		//DeviceEventEmitter.emit("dealCollection",this.state.classType);
		Toast.show("删除成功",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	},() => {
		Toast.show("删除失败",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	},() => {
		Toast.show("网络错误",{
			duration: 1000,
			position: Toast.positions.CENTER,
			shadow: true,
			animation: true,
			hideOnPress: true,
			delay: 0
		})
	});
  }
  render() {
  	let propDataLength = this.state.rows.length;
  	if(propDataLength===0){
  		return null;
  	}else{
      let marginStyle = this.state.dataLength>0 ? {
        borderTopWidth:0,
      } : {};
		return(
		<View style={styles.collectionColumn}>
      			{
      				this.state.showTitle　?　
      					<Text style={[styles.collectionCategory,{paddingBottom:ScreenUtils.scaleSize(14),borderColor:"#ededed",borderBottomWidth:1,}]}>
      						{this.state.sectionTitle}
      						{
      							this.props.totalPage ? <Text>({String(this.props.totalPage)})</Text> :null
      						}
      					</Text>　: null
      			}
      			{
      				this.props.showTotalData ?
      					<Text style={styles.collectionCategory}>
      							 <Text>共{String(this.props.totalPage)}条</Text>
      					</Text>　: null
      			}
      			<View style={[styles.Item,marginStyle]}> 
          {
            this.state.rows.map((item,key)=>{
              return this.renderInfoItems(item,key)
            })
          }
					{
						this.props.pagation ?
							<TouchableOpacity style={styles.showMore}  onPress={() => Common.onForward(this.props.chageThis,InfoSearch,InfoSearch,this.props.keywords,this.props.totalPage)}>
								<Image source = {require('../../../images/toBottom.png')}/>
								<Text style={{marginLeft:10,fontSize:ScreenUtils.scaleSize(20),}}>展开</Text>
							</TouchableOpacity> : null
					}
					
				</View>
		</View>
		)  		
  	}
  }
  
  showDeleteButton(ev,target){
  	if(this.startLocation>this.moveLocation){
  		target.scrollToEnd({animated: true});
      this.openScroll.push(target);
  	}else{
  		target.scrollTo({x:0,y:0,animated: true});
  	}
  }
  linking = (val) => {
    if(Platform.OS == 'ios'){
      NativeModules.JsAndroid.openUrl(val.url);
    }else{
      // Common.onForward(this, Article, val, 5);
      Common.onForward(this.props.chageThis,Article,val,5)
    }
  }
  renderInfoItems(data,rowID) {
  	var _scrollView: ScrollView;
  	let sourceImage ;
  	var mydata = Common.keyWordHighlight(data.title);
  	switch(data.scrabbleType){
  		case 'wechat':
  			sourceImage = wechat;
  			break;
  		case 'web':
  			sourceImage = web;
  			break;
  		default :
  			sourceImage = weibo;
  			break;
  	}
    var Vheight = ScreenUtils.scaleSize(112);

    this.state.deleteArr.map((item,key)=>{
      if(item==data.id){
        Vheight=0;
      }
    })
    return (
    <ScrollView
      	horizontal = {true}
      	showsHorizontalScrollIndicator = {false}
      	ref={(scrollView) => { _scrollView = scrollView; }}
      	onTouchStart={(event)=>{
      		this.startLocation=event.nativeEvent.pageX
      	}}
      	onTouchMove={(event)=>{
      		this.moveLocation=event.nativeEvent.pageX
      	}}
      	onScrollEndDrag={(event)=>{
      		 this.showDeleteButton(event,_scrollView);
      	}}
        style={{height:Vheight,overflow:"hidden"}}
        key={rowID}
        bounces={false}
      >
      <TouchableHighlight underlayColor="#fafafa" delayPressIn={100} style ={[styles.InfoItemContainer,{height:Vheight}]} 
      onPress={() => this.linking({title:Common.cancelHightlight(data.title),url:data.url,id:data.id})}>
      	<View style={{flex:1,flexDirection:"column",justifyContent:"space-between",}}>	
          <View style={styles.infoTitleWrap} >
      			{
      				!this.props.search ? <Text style={styles.infoTitle} numberOfLines ={1}>{data.title}</Text> :
      				<Text style={styles.infoTitle} numberOfLines ={1}>
      					{
      				        mydata.map((item,i)=>{
      				          	if(item.hightLight){
      				          		return(
      				          			<Text key={i} style={{color:"red"}}>{item.data}</Text>
      				          		)
      				          	}else{
      				          		return(
      				          			<Text key={i}>{item.data}</Text>
      				          		)
      				          	}
      				        })
      			        }
      				</Text>
      			}
      			
      		</View>
      		<View style={styles.infoAbout}>
      			<View style={styles.infoContent}>
        				<Image style={styles.infoAboutImage} source = {sourceImage}/> 
        				<Text style={styles.infoAboutText}>
        					<Text style={styles.infoText}>{data.company}</Text>
        				</Text>
        			</View>
        			<View style={styles.infoContent}>
        				<Image style={styles.infoAboutImageTimer} source = {require('../../../images/timer.png')}/> 
        				<Text style={styles.infoAboutText}>
        					<Text style={styles.infoText}>{Common.beforeTime(data.createTime,5)}</Text>
        				</Text>
        			</View>
        			{
        				data.sourceDegree ? 
        				(
        					parseFloat(data.sourceDegree)>0 ?
        						<View style={styles.infoContent}>
      			  				<Text style={styles.infoAboutText}>
      			  						<Text style={styles.infoText}>{data.sourceDegree}</Text> 阅读
      			  				</Text>
      			  			</View> :null
        				):null
        			}
      		</View>
        </View>
      </TouchableHighlight>  
     	{
	      	this.state.showDeleteButton ?
		      (
		      	<TouchableOpacity 
		      		style={styles.deleteWrap} 
		      		onPress={()=>{
		      			this.handleDelete(rowID,data.id,_scrollView)
		      			}
		      		}
		      	>
			      <Text style={styles.deleteText}>删除</Text>
			    </TouchableOpacity>
		      ):null
	    }
    </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  InfoItemContainer:{
    width:Dimensions.get('window').width,
  	backgroundColor:"#fff",
  	flexDirection:"column",
  	height:ScreenUtils.scaleSize(112),
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  	justifyContent:"space-between",
  	paddingLeft:ScreenUtils.scaleSize(30),
  	paddingRight:ScreenUtils.scaleSize(26),
  	paddingTop:ScreenUtils.scaleSize(20),
  	paddingBottom:ScreenUtils.scaleSize(20),
  },
  infoTitle:{
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#444444",
  },
  infoAbout:{
  	flexDirection:"row",
  	justifyContent:"flex-end",
  },
  infoAboutText:{
  	fontSize:ScreenUtils.scaleSize(20),
  	color:"#9d9d9d",
  	paddingLeft:3,
  },
  infoAboutImageTimer:{
  	width:ScreenUtils.scaleSize(22),
  	height:ScreenUtils.scaleSize(22),
  },
  infoAboutImage:{
  	width:ScreenUtils.scaleSize(22),
  	height:ScreenUtils.scaleSize(18),
  },
  infoContent:{
  	flexDirection:"row",
  	marginLeft:ScreenUtils.scaleSize(20),
  	justifyContent:"center",
  	alignItems:"center",
  },
  deleteWrap:{
  	width:ScreenUtils.scaleSize(132),
  	backgroundColor:"#ff4545",
  	justifyContent:"center",
  	alignItems:"center",
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  deleteText:{
  	fontSize:ScreenUtils.scaleSize(26),
  	color:"#fff",
  },
  collectionCategory:{
  	paddingLeft:ScreenUtils.scaleSize(30),
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#939393",
  	paddingTop:ScreenUtils.scaleSize(14),
  },
  Item:{
  	
  	borderColor:"#ededed",
  },
  showMore:{
  	flex:1,
  	justifyContent:"center",
  	alignItems:"center",
  	height:ScreenUtils.scaleSize(78),
  	backgroundColor:'#fff',
  	borderBottomWidth:1,
  	borderColor:'#ebebeb',
  	flexDirection:"row",
  },
  seperatorCell:{
  	backgroundColor:"#f60",
  	marginTop:-ScreenUtils.scaleSize(14)/2,
  	zIndex:-5,
  }
});